package com.ruoyi.framework.filter;

import java.io.IOException;
import java.util.Map;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * "null"和"undefined"字符串过滤器，将请求中的"null"和"undefined"字符串转换为Java的null
 * 
 * @author ruoyi
 */
public class NullStringFilter implements Filter {
    
    private static final Logger log = LoggerFactory.getLogger(NullStringFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("NullStringFilter 初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 包装请求对象，将"null"和"undefined"字符串转为Java的null
        ServletRequest requestWrapper = new NullStringRequestWrapper((HttpServletRequest) request);
        // 传递包装后的请求对象
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {
        log.info("NullStringFilter 销毁");
    }

    /**
     * 包装HttpServletRequest，将参数值为"null"或"undefined"的转换为null
     */
    private static class NullStringRequestWrapper extends HttpServletRequestWrapper {
        
        private static final Logger log = LoggerFactory.getLogger(NullStringRequestWrapper.class);
        
        public NullStringRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            return convertNullOrUndefinedString(value);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> parameterMap = super.getParameterMap();
            if (parameterMap != null) {
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    String[] values = entry.getValue();
                    if (values != null) {
                        boolean hasChanged = false;
                        for (int i = 0; i < values.length; i++) {
                            String oldValue = values[i];
                            values[i] = convertNullOrUndefinedString(values[i]);
                            if (oldValue != null && values[i] == null) {
                                hasChanged = true;
                            }
                        }
                        if (log.isTraceEnabled() && hasChanged) {
                            log.trace("参数 {} 的值中有'null'或'undefined'字符串被转换为null", entry.getKey());
                        }
                    }
                }
            }
            return parameterMap;
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = convertNullOrUndefinedString(values[i]);
                }
            }
            return values;
        }

        /**
         * 将"null"或"undefined"字符串转换为null
         * 
         * @param value 原始字符串
         * @return 转换后的值
         */
        private String convertNullOrUndefinedString(String value) {
            if (value != null) {
                String trimValue = value.trim();
                if ("null".equals(trimValue) || "undefined".equals(trimValue)) {
                    return null;
                }
            }
            return value;
        }
    }
} 